<?php

namespace app\user\controller\mall\order;

use app\user\controller\mall\Base;
use think\Db;
use app\common\model\mall\oper\Msgtpl;
use addons\mall\library\Service;
use app\common\model\mall\oper\Notification;
use think\Hook;

/**
 * 退单
 *
 * @icon fa fa-circle-o
 */
class Myrefund extends Base
{
    
    /**
     * Orderrefunds模型对象
     * @var \app\common\model\mall\order\Refunds
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\mall\order\Refund;
        $this->view->assign("refundresonList", $this->model->getRefundresonList());
        $this->view->assign("refundstatusList", $this->model->getRefundstatusList());
    }

    public function index() {

        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = $this->model->alias("c")
                ->join("__MALL_ORDER_ORDER__ o", "c.order_id=o.id", "LEFT")
                ->field("c.*,o.orderNo")
                ->where("o.user_id", $this->auth->id)
                ->where($where)
                ->count();

        $list = collection($this->model->alias("c")
                ->join("__MALL_ORDER_ORDER__ o", "c.order_id=o.id", "LEFT")
                ->field("c.*,o.orderNo")
                ->where("o.user_id", $this->auth->id)
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select())->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 用户申请退款
     */
    public function add($order_id = NULL)
    {
        $order_id?$order_id:input("get.order_id/d");
        //获取关联的定单
        $row = db('mall_order_order')->alias('o')
            ->join('__MALL_SHOP_SHOP__ s','o.shop_id=s.id','left')
            ->where(['o.status'=>['in',['canceled','rejected']],'o.id'=>$order_id,'o.user_id'=>$this->auth->id,'o.refundis'=>0])
            ->field('o.id order_id,s.name,o.shop_id,o.status,o.orderNo,o.realTotalMoney,o.payis,o.payType,o.useScore,o.scoreMoney')->find();

        if (!$row) $this->error(__('No Results were found'));

        if ($this->request->isPost()){
            $params = $this->request->post("row/a");
            if ($params){
                if ($this->dataLimit && $this->dataLimitFieldAutoFill){
                    $params[$this->dataLimitField] = $this->auth->id;
                }

                $money = (float)$params['backMoney'];
                if($money<0 || $money>$row["realTotalMoney"]) $this->error("退款金额不能小于0！");

                Db::startTrans();
                try{
                    $params['order_id'] = $order_id;
                    $params['refundTo'] = 0;
                    $params['refundStatus'] = ($row['status']=='canceled')?1:0;
                    //是否采用模型验证
                    if ($this->modelValidate){
                        $name = basename(str_replace("\\model\\", "\\validate\\", get_class($this->model)));
                        $validate = $this->modelSceneValidate ? $name . '.add' : $name;
                        $result = $this->validate($params,$validate);
                        if(true !== $result){
                            // 验证失败 输出错误信息
                            $this->error($result);
                        }
                    }
                    $result = $this->model->allowField(true)->save($params);
                    if ($result !== false){
                        $reasonData = $params['refundReson'].(($params['refundReson']==99)?" - ".$params['refundOtherReson']:"");

                        //拒收、取消申请退款的话要给商家发送信息
                        $to_user_id = \app\common\model\mall\shop\Shop::getFieldById($row['shop_id'],"user_id");
                        $to = \app\common\model\mall\shop\Extra::where("shop_id",$row['shop_id'])
                            ->field("applyLinkTel,applyLinkEmail")->find();
                        $find = ['${ORDER_NO}'];
                        $replace = [$row['orderNo']];
                        if($row['status']!="canceled"){
                            //发送消息提醒卖家
                            $content = Msgtpl::getMsgByTpl('ORDER_REFUND_CONFER', $find, $replace);
                            if ($content != '') {
                                Notification::record("客户申请退款", $content, $this->actionname, $this->controllername, $row['order_id'], $to_user_id);
                                $template_id = 1;
Hook::listen('vbot_send_msg', $template_id, [
                                    'content'         => $content,
                                    'at_mobiles'     => $to["applyLinkTel"],
                                    'is_atall'       => 0,
                                ]);
                            }
                        }else{
                            $content = Msgtpl::getMsgByTpl('PHONE_ADMIN_REFUND_ORDER', $find, $replace);
                            if ($content != '') {
                                Service::smsAdminNotice($content,'ordercomplain');
                                $template_id = 1;
Hook::listen('vbot_send_msg', $template_id, [
                                    'content'         => $content,
                                    'at_mobiles'     => $to["applyLinkTel"],
                                    'is_atall'       => 0,
                                ]);
                            }
                        }
                        Db::commit();
                        $this->success();
                    }
                    else
                    {
                        Db::rollback();
                        $this->error($this->model->getError());
                    }
                }
                catch (\think\exception\PDOException $e)
                {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->assign("row",$row);
        return $this->view->fetch();
    }

}
